package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * DishService添加菜品的同时也要调用DishFlavor添加口味
     *
     * @param dishDto
     */
    @Override
    //由于在 saveWithFlavor 方法中，进行了两次数据库的保存操作，操作了两张表，那么为了保证数据的一致性，
    // 我们需要在方法上加上注解 @Transactional来控制事务。
    @Transactional          //表现层传过来复合信息的菜品
    public void saveWithFlavor(DishDto dishDto) {
        //这里的this就是dishService
        this.save(dishDto); //添加基础的菜品数据
        /*
        dish_id并没有封装进集合flavors
        DishDto(flavors=[DishFlavor(id=null, dishId=null, name=甜味,
        value=["无糖","少糖","半糖","多糖","全糖"],
         createTime=null, updateTime=null, createUser=null, updateUser=null, isDeleted=null),
         DishFlavor(id=null, dishId=null, name=忌口, value=["不要葱","不要蒜","不要香菜","不要辣"],
          createTime=null, updateTime=null, createUser=null, updateUser=null, isDeleted=null)],
          categoryName=null, copies=null)
         */
        Long dishDtoId = dishDto.getId(); //获取菜品id
        //获取菜品口味集合
        List<DishFlavor> flavors = dishDto.getFlavors();
        //对每个对象的dishId属性 赋值
        flavors = flavors.stream().map((flavor) -> {
            flavor.setDishId(dishDtoId);
            return flavor;
        }).collect(Collectors.toList());
        //保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 修改菜品时，数据回显---根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id); //根据id查询菜品

        DishDto dishDto = new DishDto();    //第三方类
        BeanUtils.copyProperties(dish, dishDto);  //转存数据

        //查询当前菜品对应的口味信息，从dish_flavor表查询
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);

        return dishDto;
    }

    /**
     * 修改菜品(包含里面的口味)
     *
     * @param dishDto
     */
    @Override
    @Transactional // 记得开启事务
    public void updateWithFlavor(DishDto dishDto) {
        //更新dish表基本信息
        this.updateById(dishDto);

        //清理当前菜品对应口味数据---dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId()); //复合类里的DishId

        dishFlavorService.remove(queryWrapper); //根据DishId删除DishFlavor表(原来的口味)

        //添加当前提交过来的口味数据---dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 批量删除菜品，并做逻辑判断
     *
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        /*
        传过来要删除对象的菜品ids，首先判断是否在售，还要判断该菜品是否在分类 和 套餐中
        在售：提示更改状态 不能删
        在套餐中：不能删除
        在分类中：肯定有分类，直接删不用做判断
        菜品的口味: 也要删除

         */
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper();
        lqw.in(Dish::getId, ids);
        lqw.eq(Dish::getStatus, 1);
        int count = this.count(lqw); //条件1.菜品是否在售

        //select count(*) from SetmealDish where dishId in (ids)
        LambdaQueryWrapper<SetmealDish> lqw2 = new LambdaQueryWrapper<>();
        lqw2.in(SetmealDish::getDishId, ids);
        int count2 = setmealDishService.count(lqw2);//条件2.菜品是否在套餐中

        if (count > 0 || count2 > 0) {
            //关联了，不能删
            throw new CustomException("菜品正在售卖中或已关联套餐，不能删除");
        }
        //主表删除了  关系表呢？ 这里就不用删除了  因为如果关联，菜品就不能删除
        this.removeByIds(ids);
        //删完过后要删除该菜品的口味（集合）
        LambdaQueryWrapper<DishFlavor> lqw3 = new LambdaQueryWrapper<>();
        lqw3.in(DishFlavor::getDishId, ids);
        //直接根据id删除口味
        dishFlavorService.remove(lqw3);

    }
}
